<?php
namespace Service;
use OSS\OssClient;
use OSS\Core\OssException;

class OssSimple
{

    private $ossClient = null;

    private $config = [];

    /*
        $key 读取哪一项配置
        $isPublic 是否公网提交
    */
    public function setConfig($key = 'default', $isPublic = false)
    {
        $config = getConfig('oss', $key);
        $this->config = $config;
        if($isPublic){
            $endpoint = $config['end_point'];
        }
        else{
            $endpoint = $config['end_point_internal'];
        }
        $this->ossClient = new OssClient($config['access_key_id'], $config['access_key_secret'], $endpoint);
        return $this;
    }

    public function getConfig()
    {
        return $this->config;
    }

    public function upload($object = '2020/03/18/test.txt', $content = 'This is test')
    {
        $config = $this->getConfig();
        $bucket = $config['bucket'];
        try{
            $this->ossClient->putObject($bucket, $object, $content);
        }
        catch(OssException $e){
            echo $e->getMessage();
            return false;
        }
        return true;
    }

    public function delete($object = '2020/03/18/test.txt')
    {
        $config = $this->getConfig();
        $bucket = $config['bucket'];
        try{
            $this->ossClient->deleteObject($bucket, $object);
        }
        catch(OssException $e){
            echo $e->getMessage();
            return false;
        }
        return true;
    }

    public function listObjects($options = NULL)
    {
        $config = $this->getConfig();
        $bucket = $config['bucket'];
        try{
            $result = $this->ossClient->listObjects($bucket, $options);
        }
        catch(OssException $e){
            echo $e->getMessage();
            return false;
        }
        return $result;
    }

}